import React, { Component } from 'react'
import styles from "./pay.module.scss"
import Nav from "../nav/Nav";
import { connect } from "react-redux"
import { withRouter } from "react-router-dom"
import { getSearchGoodsList, createOrder, syncCart,getCart } from "../../data/api"
import { Toast } from "antd-mobile"
class Pay extends Component {
    state = {
        goodsList: [],
        totalNum: 0,
    }
    async componentDidMount() {
        // console.log(this.props);
        let id = this.props.location.pathname.split("/")[2];
        // console.log(id);
        //由购物车点击结算跳转到订单页面
        if (this.props.goodsList) {
            let obj = this.props.goodsList;
            let newObj = {};
            let totalNum = 0;
            for (let goods_id in obj) {
                //判断要结算的商品
                if (obj[goods_id].status) {
                    newObj[goods_id] = obj[goods_id];
                    totalNum += obj[goods_id].amount
                }
            }
            //转换为数组
            let goodsList = Object.values(newObj);
            this.setState({
                goodsList: goodsList,
                totalNum: totalNum,
            });
        } else if (id) {//由详情页的立即购买跳转到订单页面
            let res = await getSearchGoodsList({
                goods_id: id
            });
            res.message.status = true;
            let goodsList = [res.message];
            this.setState({
                goodsList,
            })
        }
    }
    submit = async () => {
        let goods = [];
        let cart_info;
        //分为两个部分，
        //1、从购物车结算跳转过来的
        if (this.props.goodsList) {
            //获取 仓库里的商品数据
            cart_info = this.props.goodsList;
            this.state.goodsList.map(v => {
                goods.push({
                    goods_id: v.goods_id,
                    goods_number: v.amount,
                    goods_price: v.goods_price
                });
                //提交订单的时候，要将这条订单从当前购物车中移除
                delete cart_info[v.goods_id];
            });
        } else {//2、从详情页跳转过来
            //获取购物车的数据，如果不获取购物车的数据，提交订单后购物车的数据会被清空
            let res = await getCart();
            // console.log(res);
            if(res.meta.status === 200){
                cart_info = JSON.parse(res.message.cart_info);
            }
            goods = [{
                goods_id: this.state.goodsList[0].goods_id,
                goods_number: 1,
                goods_price: this.state.goodsList[0].goods_price
            }]
            // console.log(goods);
        }
        let consignee_addr = "广东省深圳市宝安区西部硅谷"
        //发送创建订单请求
        let res = await createOrder({
            order_price: this.props.totalPrice,
            consignee_addr,
            goods
        });
        // console.log(res);
        if (res.meta.status === 200) {
            Toast.success("创建订单成功", 2, () => {
                this.props.history.push('/orderList')
            })
            //同步购物车
            syncCart({ infos: JSON.stringify(cart_info) });
            this.props.syncCartGoods(cart_info);
        }
    }
    render() {
        return (
            <div className={styles.pay}>
                <Nav title="确认订单" left={true}></Nav>
                <div className={styles.payContent}>
                    {
                        this.state.goodsList ? this.state.goodsList.map((v, i) => {
                            return <div className={styles.payGoogsItem} key={v.goods_id}>
                                <div className={styles.goodsImg}>
                                    <img src={v.goods_small_logo} alt="" />
                                </div>
                                <div className={styles.goodsDer}>
                                    <div className={styles.goodsName}>{v.goods_name}</div>
                                    <div className={styles.goodsPrice}>
                                        <span className={styles.num}>共{v.amount ? v.amount : 1}件</span>
                                        <span className={styles.price}>小计：￥{v.amount ? v.amount * v.goods_price : v.goods_price}</span>
                                    </div>
                                </div>
                            </div>
                        }) : ''
                    }
                </div>
                <div className={styles.payFooter}>
                    <div className={styles.num}>共{this.props.totalNum}件</div>
                    <div className={styles.payTotal}>合计：￥{this.props.totalPrice}</div>
                    <div className={styles.submit} onClick={this.submit}>提交订单</div>
                </div>
            </div>
        )
    }
}
const mapStateToProps = (state) => {
    // console.log(state.cartReducer);
    return {
        goodsList: state.cartReducer.goodsList,
        totalPrice: state.cartReducer.totalPrice,
        totalNum: state.cartReducer.totalNum
    }
}
const mapDispatchToProps = (dispatch) => {
    return {
        syncCartGoods: (goodsList) => {
            dispatch({
                type: "SYNC_CART_GOODS",
                payload: {
                    goodsList,
                }
            })
        }
    }
}
export default connect(mapStateToProps, mapDispatchToProps)(withRouter(Pay))